package com.app.studyroom;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.studyroom.adapter.MessageAdapter;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.messageNotice.DeleteMessageRequest;
import com.app.studyroom.api.model.messageNotice.MessageItem;
import com.app.studyroom.api.model.messageNotice.MessageStatusUpdateRequest;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MessageNoticeActivity extends BaseActivity {

    private RecyclerView recyclerView;
    private MessageAdapter adapter;
    private ImageView btnBack;
    private TextView tvPageIndicator;
    private Button btnPrevPage, btnNextPage;
    private int currentPage = 1;
    private final int pageSize = 11;
    private List<MessageItem> messageList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_notice);

        btnBack= findViewById(R.id.ic_back);
        tvPageIndicator = findViewById(R.id.tvPageIndicator);
        btnPrevPage = findViewById(R.id.btnPrevPage);
        btnNextPage = findViewById(R.id.btnNextPage);
        recyclerView = findViewById(R.id.recycler_message_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MessageAdapter(this, messageList, item -> { markMessageAsRead(item); });

        adapter.setOnDeleteListener(item -> deleteMessage(item.getId()));
        recyclerView.setAdapter(adapter);

        btnBack.setOnClickListener(v -> onBackPressed());
        btnPrevPage.setOnClickListener(v -> {
            if (currentPage > 1) {
                currentPage--;
                loadMessages();
            }
        });

        btnNextPage.setOnClickListener(v -> {
            currentPage++;
            loadMessages();
        });

        loadMessages();
    }

    private void loadMessages() {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", null);

        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getMessageList(token).enqueue(new Callback<ApiResponse<List<MessageItem>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<MessageItem>>> call, Response<ApiResponse<List<MessageItem>>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    List<MessageItem> allMessages = response.body().getData();

                    int total = allMessages.size();
                    int fromIndex = (currentPage - 1) * pageSize;
                    int toIndex = Math.min(fromIndex + pageSize, total);

                    if (fromIndex >= total) {
                        currentPage = 1;
                        fromIndex = 0;
                        toIndex = Math.min(pageSize, total);
                    }

                    messageList.clear();
                    messageList.addAll(allMessages.subList(fromIndex, toIndex));
                    adapter.notifyDataSetChanged();

                    // ⬇️ 翻页状态更新
                    tvPageIndicator.setText("第 " + currentPage + " 页");

                    boolean isFirstPage = currentPage == 1;
                    boolean isLastPage = currentPage * pageSize >= total;

                    btnPrevPage.setEnabled(!isFirstPage);
                    btnNextPage.setEnabled(!isLastPage);

                    btnPrevPage.setAlpha(!isFirstPage ? 1.0f : 0.4f);
                    btnNextPage.setAlpha(!isLastPage ? 1.0f : 0.4f);
                } else {
                    Toast.makeText(MessageNoticeActivity.this, "加载消息失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<MessageItem>>> call, Throwable t) {
                Log.e("MessageNotice", "网络请求失败", t);
                Toast.makeText(MessageNoticeActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void deleteMessage(long messageId) {
        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", null);

        if (token == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        DeleteMessageRequest request = new DeleteMessageRequest(messageId);
        apiService.deleteMessage(token, request).enqueue(new Callback<ApiResponse<Object>>() {
            @Override
            public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    Toast.makeText(MessageNoticeActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    loadMessages();
                } else {
                    Toast.makeText(MessageNoticeActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                Toast.makeText(MessageNoticeActivity.this, "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void markMessageAsRead(MessageItem item) {
        if (item.getStatus() == 1) return; // 已读无需再调用

        SharedPreferences sp = getSharedPreferences("Session", MODE_PRIVATE);
        String token = sp.getString("token", "");

        MessageStatusUpdateRequest request = new MessageStatusUpdateRequest(item.getId());

        Log.d("MessageUpdateRequest", "请求体 JSON: " + new Gson().toJson(request));
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.updateMessageStatus(token, request).enqueue(new Callback<ApiResponse<Object>>() {
            @Override
            public void onResponse(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getCode() == 200) {
                    item.setStatus(1); // 更新本地状态
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<Object>> call, Throwable t) {
                Log.e("MessageStatus", "更新失败", t);
            }
        });
    }




}
